import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/components/input/normal_input.dart';
import 'package:wallpaper/components/list_title/my_list_title.dart';
import 'package:wallpaper/components/list_title/my_list_title_model.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/pages/login/login.dart';
import 'package:wallpaper/pages/other/about_list.dart';
import 'package:wallpaper/pages/other/cache_clean.dart';
import 'package:wallpaper/pages/other/food_page.dart';
import 'package:wallpaper/pages/other/grade_pixiv.dart';
import 'package:wallpaper/pages/other/local_image.dart';
import 'package:wallpaper/pages/other/local_image_all.dart';
import 'package:wallpaper/pages/other/love_page.dart';
import 'package:wallpaper/pages/other/vidoe_page.dart';
import 'package:wallpaper/pages/theme/icon_page.dart';
import 'package:wallpaper/pages/theme/localizations_page.dart';
import 'package:wallpaper/pages/theme/theme_page.dart';
import 'package:wallpaper/themes/theme_provider.dart';
import 'package:wallpaper/tools/route_animation.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  TextEditingController controller = TextEditingController();
  bool isShow = false;
  ScrollController scrollController = ScrollController();
  String nickName = '';

  void getNickName() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      nickName = prefs.getString('nickName') ?? 'Zsnoin能';
    });
  }

  @override
  void initState() {
    super.initState();
    getNickName();
    scrollController.addListener(() {
      if (scrollController.offset > 50) {
        setState(() {
          isShow = true;
        });
      } else {
        setState(() {
          isShow = false;
        });
      }
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<MyListTitleModel> list = [
      MyListTitleModel(
        title: S.of(context).theme,
        leading: Icon(Icons.color_lens),
        route: ThemePage(),
      ),
      MyListTitleModel(
          title: S.of(context).internationalization,
          leading: Icon(Icons.language),
          route: LocalizationsPage()),
      MyListTitleModel(
        title: S.of(context).cache,
        leading: Icon(Icons.cached_sharp),
        route: CacheClean(),
      ),
      MyListTitleModel(
        title: S.of(context).grade,
        leading: Icon(Icons.signal_cellular_alt),
        route: GradePixiv(),
      ),
      MyListTitleModel(
        title: S.of(context).about,
        leading: Icon(Icons.info),
        route: AboutList(),
      ),
    ];

    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        title: isShow
            ? Row(
                children: [
                  Image.asset('lib/assets/images/icon.png',
                      width: 30, height: 30),
                  const SizedBox(width: 10),
                  Text(
                    nickName,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              )
            : null,
        actions: [
          IconButton(
            onPressed: () {
              Provider.of<ThemeProvider>(context, listen: false).toggleTheme();
            },
            icon: Icon(
              Icons.brightness_4,
              color: Theme.of(context).colorScheme.inversePrimary,
            ),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: CustomScrollView(
          controller: scrollController,
          slivers: <Widget>[
            SliverToBoxAdapter(child: _buildTitle()),
            SliverToBoxAdapter(child: SizedBox(height: 10)),
            SliverToBoxAdapter(child: _buildCard()),
            SliverToBoxAdapter(child: SizedBox(height: 10)),
            _iconList(),
            SliverToBoxAdapter(child: SizedBox(height: 10)),
            SliverToBoxAdapter(child: MyListTitle(list: list)),
            SliverToBoxAdapter(child: SizedBox(height: 60)),
          ],
        ),
      ),
    );
  }

  Widget _buildTitle() {
    return Material(
      color: Theme.of(context).colorScheme.primaryContainer,
      borderRadius: BorderRadius.all(Radius.circular(10)),
      clipBehavior: Clip.hardEdge,
      child: InkWell(
        onTap: () {
          setState(() {
            controller.text = nickName;
          });
          // 打开弹窗，修改title
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // 圆角
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(6),
                ),
                title: SizedBox(
                  child: Text(
                    '修改昵称',
                    style: TextStyle(
                      fontSize: 19,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                content: NormalInput(controller: controller),
                actions: [
                  SizedBox(
                    width: 100,
                    child: NormalButton(
                        title: '确定',
                        fontSize: 16,
                        height: 30,
                        radius: 5,
                        onPressed: () async {
                          final prefs = await SharedPreferences.getInstance();
                          setState(() {
                            nickName = controller.text;
                            prefs.setString('nickName', nickName);
                          });
                          controller.clear();
                          Navigator.of(context).pop();
                        }),
                  ),
                  SizedBox(
                    width: 100,
                    child: NormalButton(
                        title: '取消',
                        fontSize: 16,
                        height: 30,
                        radius: 5,
                        bgColor: Colors.grey,
                        onPressed: () {
                          controller.clear();
                          Navigator.of(context).pop();
                        }),
                  ),
                ],
              );
            },
          );
        },
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            spacing: 10,
            children: [
              Image(
                width: 60,
                height: 60,
                image: const AssetImage('lib/assets/images/icon.png'),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: MediaQuery.of(context).size.width - 150,
                    child: Text(
                      nickName,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Container(
                    width: MediaQuery.of(context).size.width - 130,
                    padding: EdgeInsets.only(bottom: 2),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('Lv.6'),
                        Icon(
                          Icons.whatshot_outlined,
                          size: 18,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                      ],
                    ),
                  ),
                  Container(
                    // 屏幕宽度
                    width: MediaQuery.of(context).size.width - 130,
                    height: 5,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _iconList() {
    List iconPage = [
      {'index': 48, 'title': S.of(context).video, 'page': VideoPage()},
      {'index': 6, 'title': S.of(context).local, 'page': LocalImage()},
      {
        'index': 14,
        'title': S.of(context).album,
        'page': GetAllImagesExample()
      },
      {'index': 47, 'title': S.of(context).collect, 'page': LovePage()},
      {'index': 28, 'title': S.of(context).food, 'page': FoodPage()},
      {'index': 5, 'title': S.of(context).icons, 'page': IconPage()},
      {'index': 38, 'title': S.of(context).login, 'page': Login()},
    ];
    return SliverGrid(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
      ),
      delegate: SliverChildBuilderDelegate(
        childCount: iconPage.length,
        (BuildContext context, int index) {
          return Material(
            color: Theme.of(context).colorScheme.primaryContainer,
            borderRadius: BorderRadius.circular(10),
            child: InkWell(
              borderRadius: BorderRadius.circular(10), // 设置水波纹的圆角
              onTap: () {
                RouteAnimation().animateRoute(context, iconPage[index]['page']);
              },
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                        'lib/assets/icon/${iconPage[index]['index']}.png',
                        width: 30),
                    Text(iconPage[index]['title']),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildCard() {
    return Container(
      height: 200,
      // 背景图片
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        image: DecorationImage(
          image: AssetImage('lib/assets/images/bg.jpg'),
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}
